#include <QCoreApplication>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSpacerItem>
#include <QFormLayout>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QMessageBox>
#include <QFont>
#include <QStyle>
#include <QApplication>
#include <QTimer>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QToolBar>  // 添加QToolBar支持
#include <QDialog>
#include <QTextEdit>
#include <QStandardPaths>
#include <QScrollArea>
#include <QDirIterator>
#include <QRegularExpression>
#include <QProcess>

#include <QPainter>
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>

#include "autoPackage.h"
#include "widget.h"
#include "issSource.h"  // 添加缺失的头文件以使用LINE_EDIT_STYLE等常量
#include <QDesktopServices>
#include <QUrl>
#include <QFileInfo>
#include <QMessageBox>
#include <QDebug>  // 添加调试输出支持
#include <QProcess>
#include <QRegularExpression>

QString Widget::getValidWindeployqtPath(QWidget* parent) {
    QString selectedPath;
    bool isValid = false;

    while (!isValid) {
        selectedPath = QFileDialog::getOpenFileName(
            parent,
            "选择 windeployqt.exe",
            QCoreApplication::applicationDirPath(),
            "windeployqt (windeployqt.exe);;所有文件 (*.*)"
        );

        if (selectedPath.isEmpty()) {
            return QString();
        }

        QFileInfo fileInfo(selectedPath);
        if (fileInfo.fileName().compare("windeployqt.exe", Qt::CaseInsensitive) != 0) {
            QMessageBox::warning(parent, "无效文件",
                               "必须选择 windeployqt.exe 文件！");
            continue;
        }

        QProcess process;
        process.start(selectedPath, {"--version"});
        if (!process.waitForFinished(1000)) {
            QMessageBox::warning(parent, "无效文件",
                               "文件无法执行，请选择有效的 windeployqt.exe！");
            continue;
        }

        isValid = true;
    }

    settings->setValue("WinDeployQtPath",selectedPath);

    return QDir::toNativeSeparators(selectedPath);
}

bool Widget::isWinDeployQtExist(const QString &path) {
    QFileInfo fileInfo(path);
    return fileInfo.exists() && fileInfo.isFile() && fileInfo.isExecutable();
}

bool Widget::runGuiProgram(const QString &fullPath)
{
    QString nativePath = QDir::toNativeSeparators(fullPath);

    QFileInfo fileInfo(nativePath);
    if (!fileInfo.exists()) {
        QMessageBox::critical(this, "文件不存在",
                              QString("找不到指定程序：\n%1").arg(nativePath));
        return false;
    }

#ifdef Q_OS_WIN
    if (!nativePath.endsWith(".exe", Qt::CaseInsensitive)) {
        nativePath += ".exe";
        fileInfo.setFile(nativePath);
        if (!fileInfo.exists()) {
            QMessageBox::critical(this, "错误",
                                  "必须指定 .exe 可执行文件");
            return false;
        }
    }
#endif

    bool success = false;
    QString errorMsg;

    success = QProcess::startDetached(nativePath, QStringList(), fileInfo.absolutePath());

    if (!success) {
        // 方式2：尝试通过 cmd 启动（解决某些权限问题）
        success = QProcess::execute("cmd.exe", {"/C", "start", "\"\"" , nativePath}) == 0;
        errorMsg = "程序无法启动（可能缺少权限或依赖）";
    }

    return success;
}

void Widget::runWinDeployQt() {
    const QString exePath = pathEdit->text();
    QProcess process;

    QString program = settings->value("WinDeployQtPath").toString();
    QStringList arguments;
    arguments << exePath;

    process.start(program, arguments);
    if (!process.waitForStarted()) {
        showError("Failed to start the windeployqt process.");
        return;
    }

    process.waitForFinished();
    QString output = process.readAllStandardOutput();
    QString error = process.readAllStandardError();

    // 忽略常见的警告信息，只处理真正的错误
    QStringList ignoredWarnings = {
        "Warning: Cannot find any version of the dxcomplier.dll and dxil.dll",
        "Warning: Cannot find Visual Studio installation directory, VCINSTALLDIR is not set",
        "dxcomplier.dll", "dxil.dll", "VCINSTALLDIR"
    };
    
    bool hasRealError = false;
    if (!error.isEmpty()) {
        // 检查是否是真正的错误而不是警告
        QString errorLower = error.toLower();
        bool isOnlyWarning = false;
        
        for (const QString &warning : ignoredWarnings) {
            if (errorLower.contains(warning.toLower())) {
                isOnlyWarning = true;
                break;
            }
        }
        
        // 如果包含"error"或"failed"等关键词，认为是真正的错误
        if (!isOnlyWarning && (errorLower.contains("error") || errorLower.contains("failed") || errorLower.contains("无法") || errorLower.contains("not found"))) {
            hasRealError = true;
        }
    }

    if (hasRealError) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setWindowTitle("错误");
        msgBox.setText("WinDeployQt运行出现错误：\n" + error);
        msgBox.setStandardButtons(QMessageBox::Ok);

        QObject::connect(&msgBox, &QMessageBox::buttonClicked, [&](QAbstractButton* button){
            if (button == msgBox.button(QMessageBox::Ok)) {
                getValidWindeployqtPath(this);
            }
            msgBox.close();
        });

        msgBox.exec();
        return;
    }
    
    // 如果只是警告，显示成功信息
    if (!error.isEmpty() && !hasRealError) {
        qDebug() << "WinDeployQt warnings (ignored):" << error;
    }
    qDebug() << "WinDeployQt completed successfully";
}

Widget::Widget(QWidget *parent) : QWidget(parent),settings(new QSettings(QSettings::IniFormat, QSettings::UserScope,
                             "TCT", "PackageTool")) {
    
    // 先设置菜单栏
    setupMenuBar();
    
    // 自动检测windeployqt路径（如果从未设置过）
    if (settings->value("WinDeployQtPath").isNull()) {
        QString autoPath = autoDetectWinDeployQt();
        if (!autoPath.isEmpty()) {
            settings->setValue("WinDeployQtPath", autoPath);
        }
    }
    
    // 自动检测Inno Setup路径（如果从未设置过）
    if (settings->value("InnoSetupPath").isNull()) {
        QString autoPath = autoDetectInnoSetup();
        if (!autoPath.isEmpty()) {
            settings->setValue("InnoSetupPath", autoPath);
        }
    }
    
    // 删除强制路径设置，改为自动检测
    setupUI();
    setupStyles();
    loadSettings();
    
#ifdef Q_OS_LINUX
    // Ubuntu版本检查并自动下载appimagetool
    if (!isAppimagetoolInstalled()) {
        qDebug() << "AppImageTool not found, starting automatic download...";
        downloadAppimagetool();
    }
    
    resize(700, 520); // Ubuntu版本增加窗口宽度，确保菜单栏有足够空间
#else
    resize(600, 520); // Windows版本保持原有尺寸
#endif
    setFixedSize(this->size());
    
    // 启用拖拽功能
    setAcceptDrops(true);
}

Widget::~Widget() {}

// 删除强制路径检查函数，改为自动检测模式

void Widget::loadSettings() {
    // 使用LINE_EDIT_STYLE作为基础，只调整占位符文字颜色
    QString grayHintStyle = LINE_EDIT_STYLE + "QLineEdit { color: #666666; font-style: italic; font-weight: normal; }";  // 占位符用稍浅的黑色
    QString normalInputStyle = LINE_EDIT_STYLE;  // 用户输入用正常黑色

    settings->beginGroup("PackageSettings");

    auto loadSetting = [grayHintStyle, normalInputStyle](QLineEdit* edit, const QVariant& value, const QString& hint) {
        edit->setProperty("defaultValue", value.isValid() ? value.toString() : "");
        edit->setProperty("hintText", hint);

        if(!value.toString().isEmpty()) {
            edit->setStyleSheet(normalInputStyle);  // 有内容时使用正常样式
            edit->setText(value.toString());
        } else {
            edit->setStyleSheet(grayHintStyle);  // 占位符时使用灰色文字但保持白色背景
            edit->setText(hint);
        }
        edit->setProperty("isUserInput", false);
    };

    loadSetting(nameEdit, settings->value("AppName"), "");
    loadSetting(versionEdit, settings->value("AppVersion"), "1.0.0");
    loadSetting(pathEdit, settings->value("AppPath"), "请选择程序路径");
    loadSetting(outputPathEdit, settings->value("OutputPath"), "请选择输出目录");
#ifdef Q_OS_LINUX
    loadSetting(iconEdit, settings->value("IconPath"), "请选择图标文件");
#endif

    settings->endGroup();

    // 设置事件过滤器和信号连接
    auto setupEditField = [this, normalInputStyle, grayHintStyle](QLineEdit* edit) {
        edit->installEventFilter(this);
        connect(edit, &QLineEdit::textChanged, this, [edit, normalInputStyle](){
            if(!edit->property("isUserInput").toBool()) {
                edit->setProperty("isUserInput", true);
                edit->setStyleSheet(normalInputStyle);  // 用户输入时使用正常的白色背景样式
            }
        });
        connect(edit, &QLineEdit::editingFinished, this, [edit, grayHintStyle](){
            if(edit->text().isEmpty()) {
                edit->setProperty("isUserInput", false);
                edit->setStyleSheet(grayHintStyle);  // 空白时使用灰色文字但保持白色背景
                edit->setText(edit->property("hintText").toString());
            }
        });
    };

#ifdef Q_OS_LINUX
    for(QLineEdit* edit : {nameEdit, versionEdit, pathEdit, outputPathEdit, iconEdit}) {
        setupEditField(edit);
    }
#else
    for(QLineEdit* edit : {nameEdit, versionEdit, pathEdit, outputPathEdit}) {
        setupEditField(edit);
    }
#endif
}

bool Widget::eventFilter(QObject *obj, QEvent *event) {
    // 处理输入框点击
    for(QLineEdit* edit : {nameEdit, versionEdit}) {
        if(obj == edit && event->type() == QEvent::MouseButtonPress) {
            if(!edit->property("isUserInput").toBool()) {
                edit->clear();
                edit->setProperty("isUserInput", true);
                edit->setStyleSheet(LINE_EDIT_STYLE);  // 使用完整样式而不是仅设置颜色
            }
            break;
        }
    }
    
#ifdef Q_OS_LINUX
    // 处理菜单标签点击
    QLabel* label = qobject_cast<QLabel*>(obj);
    if (label && event->type() == QEvent::MouseButtonPress) {
        if (label->objectName() == "settingsLabel") {
            showSettings();
            return true;
        } else if (label->objectName() == "aboutLabel") {
            showAbout();
            return true;
        }
    }
#endif
    
    return QWidget::eventFilter(obj, event);
}

void Widget::saveSettings() {
    settings->beginGroup("PackageSettings");
    settings->setValue("AppName", nameEdit->text());
    settings->setValue("AppVersion", versionEdit->text());
    settings->setValue("AppPath", pathEdit->text());
    settings->setValue("OutputPath", outputPathEdit->text());
#ifdef Q_OS_LINUX
    settings->setValue("IconPath", iconEdit->text());
#endif
    settings->endGroup();
}

void Widget::setupUI() {
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(15); // 减小间距
    mainLayout->setContentsMargins(0, 0, 0, 20); // 顶部边距设为0给菜单栏留空间，底部增加边距
    
    // 添加菜单栏到布局顶部
    mainLayout->addWidget(menuBar);
    
    // 添加内容容器
    QWidget *contentWidget = new QWidget(this);
    QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);
    contentLayout->setSpacing(15); // 减小间距
    contentLayout->setContentsMargins(25, 15, 25, 0); // 调整边距

    // 添加图标
    iconLabel = new QLabel(this);
    QPixmap icon(":/icons/package.png"); // 使用资源文件中的图标
    if(icon.isNull()) {
        icon = QPixmap(64, 64);
        icon.fill(Qt::transparent);
    }
    iconLabel->setPixmap(icon.scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    iconLabel->setAlignment(Qt::AlignCenter);

    // 添加艺术字标题
    titleLabel = new QLabel("AutoPack", this);
    titleLabel->setAlignment(Qt::AlignCenter);

    // 输入表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->setSpacing(12); // 减小间距
    formLayout->setContentsMargins(0, 0, 0, 0);
    formLayout->setLabelAlignment(Qt::AlignRight);

    nameEdit = new QLineEdit(this);
    versionEdit = new QLineEdit(this);
    pathEdit = new QLineEdit(this);
#ifdef Q_OS_LINUX
    iconEdit = new QLineEdit(this); // 图标路径输入框（仅Linux）
#endif
    outputPathEdit = new QLineEdit(this); // 新增输出路径输入框

    pathEdit->setReadOnly(true);
#ifdef Q_OS_LINUX
    iconEdit->setReadOnly(true); // 图标路径也设为只读（仅Linux）
#endif
    outputPathEdit->setReadOnly(true); // 输出路径也设为只读

    browseButton = new QPushButton("选择文件", this);
#ifdef Q_OS_LINUX
    iconBrowseButton = new QPushButton("选择图标", this); // 图标浏览按钮（仅Linux）
#endif
    outputBrowseButton = new QPushButton("选择路径", this); // 新增输出路径浏览按钮
    packageButton = new QPushButton("开始一键打包", this);
    
    // 设置按钮最小高度，确保文字能正常显示
    browseButton->setMinimumHeight(35);
#ifdef Q_OS_LINUX
    iconBrowseButton->setMinimumHeight(35);
#endif
    outputBrowseButton->setMinimumHeight(35);
    packageButton->setMinimumHeight(40);
    
    // 添加进度条和状态标签（始终占据空间，但平时不显示内容）
    progressBar = new QProgressBar(this);
    progressBar->setRange(0, 100);
    progressBar->setTextVisible(false); // 平时不显示文本
    progressBar->setMinimumHeight(30);
    progressBar->setMaximumHeight(30);
    progressBar->setValue(0); // 平时设为0，看起来像是空的
    progressBar->setStyleSheet(
        "QProgressBar {"
        "  border: 1px solid transparent;" // 平时边框透明
        "  border-radius: 4px;"
        "  background-color: transparent;" // 平时背景透明
        "  text-align: center;"
        "}"
        "QProgressBar::chunk {"
        "  background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4CAF50, stop:1 #45a049);"
        "  border-radius: 3px;"
        "}"
    );
    
    statusLabel = new QLabel("", this); // 平时显示空文本
    statusLabel->setAlignment(Qt::AlignCenter);
    statusLabel->setMinimumHeight(25);
    statusLabel->setMaximumHeight(25);
    statusLabel->setStyleSheet(
        "QLabel {"
        "    color: #2c3e50;"
        "    font-size: 14px;"
        "    font-weight: normal;"
        "    margin: 5px;"
        "}"
    );

    // 手动创建标签并设置黑色正常样式
    QLabel *nameLabel = new QLabel("软件名称:");
    nameLabel->setStyleSheet("color: #000000; font-weight: normal; font-size: 13px;");
    formLayout->addRow(nameLabel, nameEdit);
    
    QLabel *versionLabel = new QLabel("版本号:");
    versionLabel->setStyleSheet("color: #000000; font-weight: normal; font-size: 13px;");
    formLayout->addRow(versionLabel, versionEdit);

    QHBoxLayout *pathLayout = new QHBoxLayout();
    pathLayout->addWidget(pathEdit);
    pathLayout->addWidget(browseButton);
    QLabel *pathLabel = new QLabel("程序路径:");
    pathLabel->setStyleSheet("color: #000000; font-weight: normal; font-size: 13px;");
    formLayout->addRow(pathLabel, pathLayout);

#ifdef Q_OS_LINUX
    // 添加图标路径行（仅Linux版本）
    QHBoxLayout *iconPathLayout = new QHBoxLayout();
    iconPathLayout->addWidget(iconEdit);
    iconPathLayout->addWidget(iconBrowseButton);
    QLabel *iconPathLabel = new QLabel("程序图标:");  // 重命名避免冲突
    iconPathLabel->setStyleSheet("color: #000000; font-weight: normal; font-size: 13px;");
    formLayout->addRow(iconPathLabel, iconPathLayout);
#endif

    // 新增输出路径行
    QHBoxLayout *outputPathLayout = new QHBoxLayout();
    outputPathLayout->addWidget(outputPathEdit);
    outputPathLayout->addWidget(outputBrowseButton);
    QLabel *outputLabel = new QLabel("输出路径:");
    outputLabel->setStyleSheet("color: #000000; font-weight: normal; font-size: 13px;");
    formLayout->addRow(outputLabel, outputPathLayout);

    // 将组件添加到内容布局
    contentLayout->addWidget(iconLabel);    // 这是软件顶部的PNG图标
    contentLayout->addWidget(titleLabel);
    contentLayout->addSpacing(15); // 减小间距
    contentLayout->addLayout(formLayout);
    contentLayout->addSpacing(15); // 减小间距
    contentLayout->addWidget(packageButton);
    contentLayout->addSpacing(8); // 减小间距
    contentLayout->addWidget(progressBar);
    contentLayout->addWidget(statusLabel);
    
    // 将内容容器添加到主布局
    mainLayout->addWidget(contentWidget);

    // 初始化进度条状态（隐藏）
    hideProgressBar();

    // 连接信号槽
    connect(browseButton, &QPushButton::clicked, this, &Widget::onBrowseClicked);
#ifdef Q_OS_LINUX
    connect(iconBrowseButton, &QPushButton::clicked, this, &Widget::onIconBrowseClicked); // 图标浏览信号（仅Linux）
#endif
    connect(outputBrowseButton, &QPushButton::clicked, this, &Widget::onOutputBrowseClicked); // 新增输出路径浏览信号
    connect(packageButton, &QPushButton::clicked, this, &Widget::processAutoPackaging);
}

// 新增输出路径浏览按钮点击槽函数
void Widget::onOutputBrowseClicked() {
    QString dirPath = QFileDialog::getExistingDirectory(
        this,
        "选择输出目录",
        QDir::homePath(),
        QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks
        );

    if (!dirPath.isEmpty()) {
        outputPathEdit->setText(QDir::toNativeSeparators(dirPath));
    }
}

void Widget::setupStyles() {
    // 首先清除Widget的样式表，恢复原始状态
    this->setStyleSheet("");
    
    QPalette palette = this->palette();
    palette.setColor(QPalette::Window, QColor(240, 245, 250));
    this->setPalette(palette);
    this->setAutoFillBackground(true);

    QFont titleFont;
    // 直接使用系统字体，不加载字体文件
    QFont testFont("Arial", 20, QFont::Bold);
    if (testFont.family() == "Arial") {
        titleFont = testFont;
    } else {
        titleFont = QFont("微软雅黑", 20, QFont::Bold);
    }
    titleLabel->setFont(titleFont);
    titleLabel->setStyleSheet("color: #2c3e50;");

    QString buttonStyle = BUTTON_STYLE;

    browseButton->setStyleSheet(buttonStyle);
    outputBrowseButton->setStyleSheet(buttonStyle);
    QString packageButtonStyle = buttonStyle;  // 创建副本
    packageButton->setStyleSheet(packageButtonStyle.replace("8px 16px", "12px 24px"));
    
#ifdef Q_OS_LINUX
    iconBrowseButton->setStyleSheet(buttonStyle); // 使用原始样式，而不是被修改的样式
#endif

    QString lineEditStyle = LINE_EDIT_STYLE;

    nameEdit->setStyleSheet(lineEditStyle);
    versionEdit->setStyleSheet(lineEditStyle);
    pathEdit->setStyleSheet(lineEditStyle);
    outputPathEdit->setStyleSheet(lineEditStyle);
    
#ifdef Q_OS_LINUX
    iconEdit->setStyleSheet(lineEditStyle); // 为图标输入框设置样式
#endif
    
    // 进度条样式
    progressBar->setStyleSheet(
        "QProgressBar {"
        "    border: 2px solid #bdc3c7;"
        "    border-radius: 8px;"
        "    background-color: #ecf0f1;"
        "    text-align: center;"
        "    font-size: 13px;"
        "    font-weight: 500;"
        "    color: #2c3e50;"
        "    height: 25px;"
        "}"
        "QProgressBar::chunk {"
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "              stop:0 #3498db, stop:0.5 #5dade2, stop:1 #85c1e9);"
        "    border-radius: 6px;"
        "    margin: 2px;"
        "}"
    );
    
    // 为所有平台设置表单标签的黑体样式，使用!important强制应用
    this->setStyleSheet(this->styleSheet() + 
        "QFormLayout QLabel { color: #000000 !important; font-weight: bold !important; font-size: 13px !important; }"
    );

#ifdef Q_OS_LINUX
    // Ubuntu版本额外的文字颜色修复，使用!important强制应用
    this->setStyleSheet(this->styleSheet() + 
        "QFormLayout QLabel { color: #000000 !important; font-weight: bold !important; }"  // 表单标签黑色黑体
    );
#endif
}

void Widget::onBrowseClicked() {
    QString filePath = QFileDialog::getOpenFileName(
        this,
        "选择程序文件",
        QDir::homePath(),
#ifdef Q_OS_WIN
        "可执行文件 (*.exe);;所有文件 (*)"
#else
        "可执行文件 (*);;所有文件 (*)"
#endif
        );
    if (!filePath.isEmpty()) {
        pathEdit->setText(filePath);
    }
}

#ifdef Q_OS_LINUX
void Widget::onIconBrowseClicked() {
    QString iconPath = QFileDialog::getOpenFileName(
        this,
        "选择程序图标",
        QDir::homePath(),
        "图标文件 (*.ico *.png *.svg *.jpg *.jpeg);;所有文件 (*)"
        );
    if (!iconPath.isEmpty()) {
        iconEdit->setText(iconPath);
    }
}
#endif

void Widget::onPackageClicked() {
    if (nameEdit->text().isEmpty()) {
        showError("软件名称不能为空！");
        nameEdit->setFocus();
        return;
    }

    // 验证版本号（允许空值但需要符合格式）
    QRegularExpression versionRegex("^\\d+(\\.\\d+)*$");
    if (!versionEdit->text().isEmpty() && !versionRegex.match(versionEdit->text()).hasMatch()) {
        showError("版本号格式不正确！\n示例：1.0 或 2.1.5");
        versionEdit->setFocus();
        return;
    }

    // 验证程序路径
    QString appPath = pathEdit->text();
    if (appPath.isEmpty()) {
        showError("请选择程序路径！");
        onBrowseClicked(); // 自动打开文件选择对话框
        return;
    }

    QFileInfo appFile(appPath);
    if (!appFile.exists()) {
        showError(QString("程序路径不存在！\n%1").arg(appPath));
        onBrowseClicked(); // 自动打开文件选择对话框
        return;
    }
    if (!appFile.isFile()) {
        showError("必须选择文件而非目录！");
        onBrowseClicked();
        return;
    }

#ifdef Q_OS_LINUX
    // Ubuntu版本必须提供程序图标
    QString iconPath = iconEdit->text();
    if (iconPath.isEmpty()) {
        showError("Ubuntu版本必须提供程序图标！\n请选择图标文件(.ico/.png/.svg等)");
        onIconBrowseClicked(); // 自动打开图标选择对话框
        return;
    }

    // 验证图标文件是否存在
    QFileInfo iconFile(iconPath);
    if (!iconFile.exists()) {
        showError(QString("程序图标文件不存在！\n%1").arg(iconPath));
        onIconBrowseClicked(); // 自动打开图标选择对话框
        return;
    }
    if (!iconFile.isFile()) {
        showError("必须选择图标文件而非目录！");
        onIconBrowseClicked();
        return;
    }

    // 验证图标文件格式
    QString iconSuffix = iconFile.suffix().toLower();
    QStringList supportedFormats = {"ico", "png", "svg", "jpg", "jpeg"};
    if (!supportedFormats.contains(iconSuffix)) {
        showError(QString("不支持的图标格式！\n支持的格式：%1\n当前文件：%2")
                 .arg(supportedFormats.join(", "))
                 .arg(iconFile.fileName()));
        onIconBrowseClicked();
        return;
    }
#endif

    // 验证输出路径
    QString outputPath1 = outputPathEdit->text();
    if (outputPath1.isEmpty()) {
        showError("请选择输出路径！");
        onOutputBrowseClicked(); // 自动打开目录选择对话框
        return;
    }

    QDir outputDir(outputPath1);
    if (!outputDir.exists()) {
        showError("目录不存在！");
        onOutputBrowseClicked(); // 自动打开目录选择对话框
        return;
    }

    saveSettings();
    QString softwareName = nameEdit->text();
    QString softwareVersion = versionEdit->text();
    QString programPath = QDir::toNativeSeparators(pathEdit->text());
    QString outputPath = QDir::toNativeSeparators(outputPathEdit->text());

    // 生成ISS脚本
    autoPackage::getInstance().run(softwareName.toStdString(),softwareVersion.toStdString(),QFileInfo(programPath).baseName().toStdString(),QFileInfo(programPath).absolutePath().toStdString(),outputPath.toStdString());

    // 检测是否是Qt程序，只对Qt程序运行windeployqt（静默处理）
    bool isQtApp = isQtApplication(programPath);
    if (isQtApp) {
        // 检查windeployqt是否配置正确
        QString windeployqtPath = settings->value("WinDeployQtPath").toString();
        if (!windeployqtPath.isEmpty() && isWinDeployQtExist(windeployqtPath)) {
            // windeployqt已正确配置，静默运行
            runWinDeployQt();
        }
        // 如果windeployqt未配置，静默跳过，不提示用户
    }

    showFancySuccessDialog(this);
}

void Widget::showProgressBar() {
    // 显示进度条和状态标签
    progressBar->setVisible(true);
    statusLabel->setVisible(true);
    progressBar->setTextVisible(true);
    progressBar->setStyleSheet(
        "QProgressBar {"
        "  border: 1px solid #ccc;"
        "  border-radius: 4px;"
        "  background-color: #f0f0f0;"
        "  text-align: center;"
        "}"
        "QProgressBar::chunk {"
        "  background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4CAF50, stop:1 #45a049);"
        "  border-radius: 3px;"
        "}"
    );
}

void Widget::hideProgressBar() {
    // 完全隐藏进度条和状态标签
    progressBar->setVisible(false);
    statusLabel->setVisible(false);
}


void Widget::processAutoPackaging() {
#ifdef Q_OS_LINUX
    processUbuntuPackaging();
#else
    processWindowsPackaging();
#endif
}

#ifdef Q_OS_LINUX
void Widget::processUbuntuPackaging() {
    // Ubuntu版本的打包逻辑
    // 验证输入
    if (nameEdit->text().isEmpty()) {
        showError("软件名称不能为空！");
        nameEdit->setFocus();
        return;
    }

    QRegularExpression versionRegex("^\\d+(\\.\\d+)*$");
    if (!versionEdit->text().isEmpty() && !versionRegex.match(versionEdit->text()).hasMatch()) {
        showError("版本号格式不正确！\n示例：1.0 或 2.1.5");
        versionEdit->setFocus();
        return;
    }

    QString appPath = pathEdit->text();
    if (appPath.isEmpty()) {
        showError("请选择程序路径！");
        onBrowseClicked();
        return;
    }

    QFileInfo appFile(appPath);
    if (!appFile.exists()) {
        showError(QString("程序路径不存在！\n%1").arg(appPath));
        onBrowseClicked();
        return;
    }
    if (!appFile.isFile()) {
        showError("必须选择文件而非目录！");
        onBrowseClicked();
        return;
    }

    // Ubuntu版本必须提供程序图标
    QString iconPath = iconEdit->text();
    if (iconPath.isEmpty()) {
        showError("Ubuntu版本必须提供程序图标！\n请选择图标文件(.ico/.png/.svg等)");
        onIconBrowseClicked();
        return;
    }

    QFileInfo iconFile(iconPath);
    if (!iconFile.exists()) {
        showError(QString("程序图标文件不存在！\n%1").arg(iconPath));
        onIconBrowseClicked();
        return;
    }
    if (!iconFile.isFile()) {
        showError("必须选择图标文件而非目录！");
        onIconBrowseClicked();
        return;
    }

    QString iconSuffix = iconFile.suffix().toLower();
    QStringList supportedFormats = {"ico", "png", "svg", "jpg", "jpeg"};
    if (!supportedFormats.contains(iconSuffix)) {
        showError(QString("不支持的图标格式！\n支持的格式：%1\n当前文件：%2")
                 .arg(supportedFormats.join(", "))
                 .arg(iconFile.fileName()));
        onIconBrowseClicked();
        return;
    }

    QString outputPath1 = outputPathEdit->text();
    if (outputPath1.isEmpty()) {
        showError("请选择输出路径！");
        onOutputBrowseClicked();
        return;
    }

    QDir outputDir(outputPath1);
    if (!outputDir.exists()) {
        showError("目录不存在！");
        onOutputBrowseClicked();
        return;
    }

    // 开始Ubuntu AppImage打包流程
    saveSettings();
    
    // 第一步：激活进度条显示
    showProgressBar();
    updatePackageButtonState("正在准备打包...", false);
    progressBar->setValue(10);
    statusLabel->setText("📦 正在准备 AppImage 打包...");
    
    QApplication::processEvents(); // 刷新界面
    
    // 获取参数
    QString softwareName = nameEdit->text();
    QString softwareVersion = versionEdit->text();
    QString programPath = QDir::toNativeSeparators(pathEdit->text());
    QString outputPath = QDir::toNativeSeparators(outputPathEdit->text());
    
    // 检查是否为Qt应用
    bool isQtApp = isQtApplication(programPath);
    
    // 第二步：调用AppImage打包逻辑
    progressBar->setValue(30);
    if (isQtApp) {
        statusLabel->setText("🔧 正在调用 Qt AppImage 打包脚本...");
        updatePackageButtonState("正在生成Qt AppImage...", false);
    } else {
        statusLabel->setText("🔧 正在调用非Qt AppImage 打包脚本...");
        updatePackageButtonState("正在生成非Qt AppImage...", false);
    }
    QApplication::processEvents();
    
    // 根据应用类型选择不同的打包方法
    if (isQtApp) {
        // Qt应用使用linuxdeployqt
        autoPackage::getInstance().runAppImagePackaging(
            softwareName.toStdString(),
            softwareVersion.toStdString(),
            QFileInfo(programPath).baseName().toStdString(),
            programPath.toStdString(),
            iconPath.toStdString(),
            outputPath.toStdString(),
            this  // 传递this作为parent，用于接收回调
        );
    } else {
        // 非Qt应用直接使用appimagetool
        autoPackage::getInstance().runNonQtAppImagePackaging(
            softwareName.toStdString(),
            softwareVersion.toStdString(),
            QFileInfo(programPath).baseName().toStdString(),
            programPath.toStdString(),
            iconPath.toStdString(),
            outputPath.toStdString(),
            this  // 传递this作为parent，用于接收回调
        );
    }
    
    // 第三步：等待异步完成，不再立即显示完成信息
    progressBar->setValue(90);
    statusLabel->setText("🔧 正在生成 AppImage 包...");
    updatePackageButtonState("正在生成AppImage...", false);
    QApplication::processEvents();
    
    // 注意：不再立即显示完成弹窗，等待异步回调
}
#endif

#ifndef Q_OS_LINUX
void Widget::processWindowsPackaging() {
    // 验证输入
    if (nameEdit->text().isEmpty()) {
        showError("软件名称不能为空！");
        nameEdit->setFocus();
        return;
    }

    QRegularExpression versionRegex("^\\d+(\\.\\d+)*$");
    if (!versionEdit->text().isEmpty() && !versionRegex.match(versionEdit->text()).hasMatch()) {
        showError("版本号格式不正确！\n示例：1.0 或 2.1.5");
        versionEdit->setFocus();
        return;
    }

    QString appPath = pathEdit->text();
    if (appPath.isEmpty()) {
        showError("请选择程序路径！");
        onBrowseClicked();
        return;
    }

    QFileInfo appFile(appPath);
    if (!appFile.exists()) {
        showError(QString("程序路径不存在！\n%1").arg(appPath));
        onBrowseClicked();
        return;
    }
    if (!appFile.isFile()) {
        showError("必须选择文件而非目录！");
        onBrowseClicked();
        return;
    }

    QString outputPath1 = outputPathEdit->text();
    if (outputPath1.isEmpty()) {
        showError("请选择输出路径！");
        onOutputBrowseClicked();
        return;
    }

    QDir outputDir(outputPath1);
    if (!outputDir.exists()) {
        showError("目录不存在！");
        onOutputBrowseClicked();
        return;
    }

    // 开始一条龙处理
    saveSettings();
    
    // 第一步：激活进度条显示
    showProgressBar();
    updatePackageButtonState("正在生成脚本...", false);
    progressBar->setValue(10);
    statusLabel->setText("📝 正在生成 Inno Setup 脚本...");
    
    QApplication::processEvents(); // 刷新界面
    
    // 生成ISS脚本
    QString softwareName = nameEdit->text();
    QString softwareVersion = versionEdit->text();
    QString programPath = QDir::toNativeSeparators(pathEdit->text());
    QString outputPath = QDir::toNativeSeparators(outputPathEdit->text());
    
    autoPackage::getInstance().run(softwareName.toStdString(),softwareVersion.toStdString(),QFileInfo(programPath).baseName().toStdString(),QFileInfo(programPath).absolutePath().toStdString(),outputPath.toStdString());
    
    // 第二步：检测Qt程序并处理
    progressBar->setValue(30);
    statusLabel->setText("🔍 检测程序类型...");
    QApplication::processEvents();
    
    bool isQtApp = isQtApplication(programPath);
    if (isQtApp) {
        QString windeployqtPath = settings->value("WinDeployQtPath").toString();
        if (!windeployqtPath.isEmpty() && isWinDeployQtExist(windeployqtPath)) {
            updatePackageButtonState("正在部署依赖库...", false);
            progressBar->setValue(50);
            statusLabel->setText("⚙️ 正在运行 WinDeployQt...");
            QApplication::processEvents();
            runWinDeployQt();
        }
    }
    
    // 第三步：编译安装包
    progressBar->setValue(70);
    statusLabel->setText("🔨 正在编译安装包...");
    updatePackageButtonState("正在编译安装包...", false);
    QApplication::processEvents();
    QString issPath = QDir::toNativeSeparators(outputPath) + "\\" + softwareName + ".iss";
    
    // 异步编译
    compileInstaller(issPath);
}
#endif

void Widget::compileInstaller(const QString &issPath) {
    // 优先使用用户设置的Inno Setup路径
    QString innoSetupPath = settings->value("InnoSetupPath").toString();
    
    if (!innoSetupPath.isEmpty()) {
        // 如果设置了路径，直接使用
        if (innoSetupPath == "ISCC" || QFileInfo(innoSetupPath).exists()) {
            startCompilation(innoSetupPath, issPath);
            return;
        }
    }
    
    // 如果没有设置或设置的路径无效，尝试自动检测
    QString autoPath = autoDetectInnoSetup();
    if (!autoPath.isEmpty()) {
        settings->setValue("InnoSetupPath", autoPath);
        startCompilation(autoPath, issPath);
        return;
    }
    
    // 都失败了，显示错误
    progressBar->setValue(0);
    statusLabel->setText("❌ 未找到编译器");
    updatePackageButtonState("未找到编译器", false);
    
    showError("未找到 Inno Setup 编译器。\n\n"
             "请在设置中配置 Inno Setup 编译器路径，\n"
             "或确保 ISCC.exe 在系统 PATH 中。");
             
    QTimer::singleShot(2000, this, [this]() {
        resetPackageButtonState();
    });
}

void Widget::startCompilation(const QString &isccPath, const QString &issPath) {
    progressBar->setValue(80);
    statusLabel->setText("⚡ 正在编译中...");
    
    QProcess *compileProcess = new QProcess(this);
    
    connect(compileProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [this, issPath, compileProcess, isccPath](int exitCode, QProcess::ExitStatus exitStatus) {
                compileProcess->deleteLater();
                
                if (exitCode == 0 && exitStatus == QProcess::NormalExit) {
                    // 编译成功
                    progressBar->setValue(100);
                    statusLabel->setText("✅ 安装包编译完成！");
                    updatePackageButtonState("编译完成！", false);
                    
                    // 2秒后重置按钮状态
                    QTimer::singleShot(2000, this, [this]() {
                        resetPackageButtonState();
                        
                        // 询问是否打开输出目录
                        QString outputDir = QFileInfo(outputPathEdit->text()).absolutePath();
                        QMessageBox::StandardButton reply = QMessageBox::question(this, 
                            "编译完成", 
                            QString("安装包编译完成！\n\n输出目录：%1\n\n是否打开输出目录？").arg(outputDir),
                            QMessageBox::Yes | QMessageBox::No);
                            
                        if (reply == QMessageBox::Yes) {
                            QDesktopServices::openUrl(QUrl::fromLocalFile(outputDir));
                        }
                    });
                } else {
                    // 编译失败
                    progressBar->setValue(0);
                    statusLabel->setText("❌ 编译失败");
                    updatePackageButtonState("编译失败", false);
                    
                    QString error = compileProcess->readAllStandardError();
                    QString output = compileProcess->readAllStandardOutput();
                    showError(QString("安装包编译失败！\n\n错误信息：\n%1\n\n输出信息：\n%2").arg(error, output));
                    
                    QTimer::singleShot(2000, this, [this]() {
                        resetPackageButtonState();
                    });
                }
            });
    
    compileProcess->start(isccPath, QStringList() << issPath);
}

void Widget::updatePackageButtonState(const QString &text, bool enabled) {
    packageButton->setText(text);
    packageButton->setEnabled(enabled);
    if (!enabled) {
        packageButton->setStyleSheet(
            "QPushButton {"
            "    background-color: #95a5a6;"
            "    color: white;"
            "    border: none;"
            "    padding: 12px 24px;"
            "    border-radius: 4px;"
            "    font-weight: bold;"
            "}"
        );
    }
}

void Widget::resetPackageButtonState() {
    packageButton->setText("开始一键打包");
    packageButton->setEnabled(true);
    hideProgressBar(); // 使用新的隐藏方法
    
    QString buttonStyle = BUTTON_STYLE;
    packageButton->setStyleSheet(buttonStyle.replace("8px 16px", "12px 24px"));
}

void Widget::showError(const QString &message) {
    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Critical);
    msgBox.setWindowTitle("错误");
    msgBox.setText(message);
    msgBox.exec();
}

void Widget::openIssFile(const QString& filePath) {
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists() || !fileInfo.isFile()) {
        QMessageBox::critical(nullptr, "错误", "指定的ISS文件不存在！");
        return;
    }

    if (fileInfo.suffix().toLower() != "iss") {
        QMessageBox::warning(nullptr, "警告", "文件不是ISS脚本格式！");
    }

    QUrl fileUrl = QUrl::fromLocalFile(fileInfo.absoluteFilePath());

    if (!QDesktopServices::openUrl(fileUrl)) {
        QProcess process;
#ifdef Q_OS_WIN
        QString program = "notepad.exe";
#else
        QString program = "gedit";  // Linux下使用gedit，可根据需要修改
#endif
        QStringList arguments;
        arguments << fileInfo.absoluteFilePath();

        if (!process.startDetached(program, arguments)) {
            QMessageBox::critical(nullptr, "错误",
                                  QString("无法打开文件！\n请确保系统已关联.iss文件的打开程序。\n路径：%1").arg(filePath));
        }
    }
}


void Widget::test(){
    QMessageBox *msgBox = new QMessageBox(this);
    msgBox->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
    msgBox->setAttribute(Qt::WA_TranslucentBackground);

    // 现代化UI样式
    msgBox->setStyleSheet(MSG_STYLE);

    // 自定义图标（使用SVG或高质量PNG）
    QPixmap icon(64, 64);
    icon.fill(Qt::transparent);
    {
        QPainter painter(&icon);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setBrush(QColor(74, 144, 226));
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(0, 0, 64, 64);
        painter.setPen(QPen(Qt::white, 3));
        painter.drawLine(20, 32, 30, 42);
        painter.drawLine(30, 42, 44, 22);
    }
    msgBox->setIconPixmap(icon);

    // 第一阶段消息（带HTML格式）
    msgBox->setText(R"(
        <html>
        <center>
            <div style='font-size:18px; font-weight:600; color:#2c3e50; margin-bottom:8px;'>
                正在生成安装包
            </div>
            <div style='color:#7f8c8d;'>
                请稍候，这通常只需要几秒钟...
            </div>
        </center>
        </html>
    )");

    // 添加淡入动画
    QGraphicsOpacityEffect *fadeEffect = new QGraphicsOpacityEffect(msgBox);
    msgBox->setGraphicsEffect(fadeEffect);
    QPropertyAnimation *fadeIn = new QPropertyAnimation(fadeEffect, "opacity");
    fadeIn->setDuration(300);
    fadeIn->setStartValue(0);
    fadeIn->setEndValue(1);
    fadeIn->start(QPropertyAnimation::DeleteWhenStopped);

    // 显示消息框
    msgBox->show();
    msgBox->adjustSize();  // 确保样式正确应用
}

void Widget::showFancySuccessDialog(QWidget* parent)
{
    QMessageBox* msgBox = new QMessageBox(parent);
    msgBox->setWindowFlags(msgBox->windowFlags() | Qt::WindowStaysOnTopHint);

    // 设置无边框和半透明背景
    msgBox->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
    msgBox->setAttribute(Qt::WA_TranslucentBackground);
    msgBox->setAttribute(Qt::WA_DeleteOnClose);


    // 花哨的样式表
    msgBox->setStyleSheet(MSG_STYLE_2);

    // 设置图标（使用彩色图标）
    QPixmap icon(64, 64);
    icon.fill(Qt::transparent);
    {
        QPainter painter(&icon);
        painter.setRenderHint(QPainter::Antialiasing);

        // 绘制渐变背景圆
        QRadialGradient grad(32, 32, 32);
        grad.setColorAt(0, QColor(255, 255, 255, 200));
        grad.setColorAt(1, QColor(255, 255, 255, 0));
        painter.setBrush(grad);
        painter.drawEllipse(0, 0, 64, 64);

        // 绘制对勾
        painter.setPen(QPen(QColor(76, 175, 80), 4));
        painter.drawLine(20, 32, 30, 42);
        painter.drawLine(30, 42, 44, 22);
    }
    msgBox->setIconPixmap(icon);

    // 设置消息文本
    msgBox->setText("<h2 style='color:black;'>打包脚本生成成功!</h2>"
                    "<p style='font-size:14px;color:black;font-weight:bold;'>选择下一步操作</p>");

    // 添加多个按钮
    QPushButton* compileButton = msgBox->addButton("编译安装包", QMessageBox::AcceptRole);
    QPushButton* openScriptButton = msgBox->addButton("打开脚本", QMessageBox::AcceptRole);
    QPushButton* okButton = msgBox->addButton("稍后处理", QMessageBox::RejectRole);
    
    compileButton->setCursor(Qt::PointingHandCursor);
    openScriptButton->setCursor(Qt::PointingHandCursor);
    okButton->setCursor(Qt::PointingHandCursor);


    // 添加淡入动画
    QGraphicsOpacityEffect* effect = new QGraphicsOpacityEffect(msgBox);
    msgBox->setGraphicsEffect(effect);

    QPropertyAnimation* fadeIn = new QPropertyAnimation(effect, "opacity");
    fadeIn->setDuration(800);
    fadeIn->setStartValue(0);
    fadeIn->setEndValue(1);
    fadeIn->setEasingCurve(QEasingCurve::InOutQuad);


    // 显示消息框
    msgBox->show();
    fadeIn->start(QPropertyAnimation::DeleteWhenStopped);

    // 按钮点击处理
    QObject::connect(compileButton, &QPushButton::clicked, [msgBox, this]() {
        QString issPath = QDir::toNativeSeparators(outputPathEdit->text()) + "\\" + nameEdit->text() + ".iss";
        
        QPropertyAnimation* fadeOut = new QPropertyAnimation(msgBox->graphicsEffect(), "opacity");
        fadeOut->setDuration(500);
        fadeOut->setStartValue(1);
        fadeOut->setEndValue(0);
        fadeOut->setEasingCurve(QEasingCurve::InOutQuad);

        QObject::connect(fadeOut, &QPropertyAnimation::finished, msgBox, &QMessageBox::close);
        fadeOut->start(QPropertyAnimation::DeleteWhenStopped);
        
        // 直接编译ISS脚本
        runInnoSetupCompiler(issPath);
    });
    
    QObject::connect(openScriptButton, &QPushButton::clicked, [msgBox, this]() {
        QString issPath = QDir::toNativeSeparators(outputPathEdit->text()) + "\\" + nameEdit->text() + ".iss";
        
        QPropertyAnimation* fadeOut = new QPropertyAnimation(msgBox->graphicsEffect(), "opacity");
        fadeOut->setDuration(500);
        fadeOut->setStartValue(1);
        fadeOut->setEndValue(0);
        fadeOut->setEasingCurve(QEasingCurve::InOutQuad);

        QObject::connect(fadeOut, &QPropertyAnimation::finished, msgBox, &QMessageBox::close);
        fadeOut->start(QPropertyAnimation::DeleteWhenStopped);
        
        // 打开ISS脚本
        openIssFile(issPath);
    });

    // 点击"稍后处理"按钮后淡出关闭
    QObject::connect(okButton, &QPushButton::clicked, [msgBox]() {
        QPropertyAnimation* fadeOut = new QPropertyAnimation(msgBox->graphicsEffect(), "opacity");
        fadeOut->setDuration(500);
        fadeOut->setStartValue(1);
        fadeOut->setEndValue(0);
        fadeOut->setEasingCurve(QEasingCurve::InOutQuad);

        QObject::connect(fadeOut, &QPropertyAnimation::finished, msgBox, &QMessageBox::close);
        fadeOut->start(QPropertyAnimation::DeleteWhenStopped);
    });

    // 5秒后自动开始淡出（可选） - 移除自动淡出，让用户主动选择
    // QTimer::singleShot(3000, msgBox, [msgBox,this]() {
    //     if (msgBox->isVisible()) {
    //         QPropertyAnimation* autoFadeOut = new QPropertyAnimation(msgBox->graphicsEffect(), "opacity");
    //         autoFadeOut->setDuration(800);
    //         autoFadeOut->setStartValue(1);
    //         autoFadeOut->setEndValue(0);
    //         QObject::connect(autoFadeOut, &QPropertyAnimation::finished, msgBox, &QMessageBox::close);
    //         autoFadeOut->start(QPropertyAnimation::DeleteWhenStopped);
    //         openIssFile(QDir::toNativeSeparators(outputPathEdit->text())+"\\"+nameEdit->text()+".iss");
    //     }
    // });
}

// 拖拽事件处理函数
void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    // 检查拖拽的数据是否包含文件URL
    if (event->mimeData()->hasUrls()) {
        const QList<QUrl> urls = event->mimeData()->urls();
        
        // 只接受单个文件
        if (urls.size() == 1) {
            const QUrl &url = urls.first();
            // 检查是否为本地文件
            if (url.isLocalFile()) {
                QString filePath = url.toLocalFile();
                QFileInfo fileInfo(filePath);
                
#ifdef Q_OS_WIN
                // Windows下只接受.exe文件
                if (fileInfo.isFile() && 
                    fileInfo.suffix().toLower() == "exe") {
                    event->acceptProposedAction();
                    
                    // 设置拖拽时的视觉反馈
                    setStyleSheet("Widget { border: 2px dashed #3498db; background-color: rgba(52, 152, 219, 0.1); }");
                    return;
                }
#else
                // Linux下接受所有可执行文件
                if (fileInfo.isFile() && fileInfo.isExecutable()) {
                    event->acceptProposedAction();
                    
                    // 设置拖拽时的视觉反馈
                    setStyleSheet("Widget { border: 2px dashed #3498db; background-color: rgba(52, 152, 219, 0.1); }");
                    return;
                }
#endif
            }
        }
    }
    
    // 拒绝拖拽
    event->ignore();
}

void Widget::dragMoveEvent(QDragMoveEvent *event)
{
    // 检查拖拽的数据是否包含有效的可执行文件
    if (event->mimeData()->hasUrls()) {
        const QList<QUrl> urls = event->mimeData()->urls();
        if (urls.size() == 1) {
            const QUrl &url = urls.first();
            if (url.isLocalFile()) {
                QString filePath = url.toLocalFile();
                QFileInfo fileInfo(filePath);
#ifdef Q_OS_WIN
                // Windows下检查.exe文件
                if (fileInfo.isFile() && fileInfo.suffix().toLower() == "exe") {
                    event->acceptProposedAction();
                    return;
                }
#else
                // Linux下检查可执行文件
                if (fileInfo.isFile() && fileInfo.isExecutable()) {
                    event->acceptProposedAction();
                    return;
                }
#endif
            }
        }
    }
    event->ignore();
}

void Widget::dropEvent(QDropEvent *event)
{
    // 恢复原始样式
    setupStyles();
    
    if (event->mimeData()->hasUrls()) {
        const QList<QUrl> urls = event->mimeData()->urls();
        if (urls.size() == 1) {
            const QUrl &url = urls.first();
            if (url.isLocalFile()) {
                QString filePath = url.toLocalFile();
                QFileInfo fileInfo(filePath);
                
#ifdef Q_OS_WIN
                // Windows下处理.exe文件
                if (fileInfo.isFile() && fileInfo.suffix().toLower() == "exe") {
                    // 设置文件路径到路径输入框
                    pathEdit->setText(QDir::toNativeSeparators(filePath));
                    pathEdit->setProperty("isUserInput", true);
                    pathEdit->setStyleSheet(LINE_EDIT_STYLE);  // 使用完整样式
                    
                    // 自动填充软件名称（总是更新为当前拖拽文件的名称）
                    QString baseName = fileInfo.baseName();
                    nameEdit->setText(baseName);
                    nameEdit->setProperty("isUserInput", true);
                    nameEdit->setStyleSheet(LINE_EDIT_STYLE);  // 使用完整样式
                    
                    event->acceptProposedAction();
                    return;
                }
#else
                // Linux下处理可执行文件
                if (fileInfo.isFile() && fileInfo.isExecutable()) {
                    // 设置文件路径到路径输入框
                    pathEdit->setText(QDir::toNativeSeparators(filePath));
                    pathEdit->setProperty("isUserInput", true);
                    pathEdit->setStyleSheet(LINE_EDIT_STYLE);  // 使用完整样式
                    
                    // 自动填充软件名称（总是更新为当前拖拽文件的名称）
                    QString baseName = fileInfo.baseName();
                    nameEdit->setText(baseName);
                    nameEdit->setProperty("isUserInput", true);
                    nameEdit->setStyleSheet(LINE_EDIT_STYLE);  // 使用完整样式
                    
                    event->acceptProposedAction();
                    return;
                }
#endif
            }
        }
    }
    
    // 如果到这里说明文件无效
#ifdef Q_OS_WIN
    QMessageBox::warning(this, "拖拽失败", 
        "请拖拽有效的.exe可执行文件！");
#else
    QMessageBox::warning(this, "拖拽失败", 
        "请拖拽有效的可执行文件！");
#endif
    event->ignore();
}

void Widget::dragLeaveEvent(QDragLeaveEvent *event)
{
    // 当拖拽离开窗口时恢复原始样式
    setupStyles();
    event->accept();
}

void Widget::setupMenuBar()
{
#ifdef Q_OS_LINUX
    // Ubuntu下使用QToolBar但放置QLabel文字而不是按钮
    menuBar = reinterpret_cast<QMenuBar*>(new QToolBar(this));
    QToolBar* toolBar = reinterpret_cast<QToolBar*>(menuBar);
    toolBar->setFixedHeight(50);  // 增加高度确保文字显示完整
    toolBar->setMovable(false);
    
    // 创建可点击的文字标签
    QLabel* settingsLabel = new QLabel("设置", this);
    QLabel* aboutLabel = new QLabel("关于", this);
    
    // 设置文字样式
    QString labelStyle = 
        "QLabel { "
        "  color: black; "
        "  font-weight: bold; "
        "  font-size: 16px; "
        "  padding: 15px 20px; "        // 上下padding相等确保垂直居中
        "  margin: 0px; "               // 移除外边距
        "  border-radius: 5px; "
        "  min-width: 60px; "
        "}"
        "QLabel:hover { "
        "  background-color: #e9ecef; "
        "}";
    
    settingsLabel->setStyleSheet(labelStyle);
    aboutLabel->setStyleSheet(labelStyle);
    
    // 设置鼠标指针样式
    settingsLabel->setCursor(Qt::PointingHandCursor);
    aboutLabel->setCursor(Qt::PointingHandCursor);
    
    // 设置文字对齐 - 水平和垂直都居中
    settingsLabel->setAlignment(Qt::AlignCenter);
    aboutLabel->setAlignment(Qt::AlignCenter);
    
    // 使标签可点击
    settingsLabel->setAttribute(Qt::WA_Hover, true);
    aboutLabel->setAttribute(Qt::WA_Hover, true);
    settingsLabel->installEventFilter(this);
    aboutLabel->installEventFilter(this);
    
    // 设置对象名称以便事件过滤器识别
    settingsLabel->setObjectName("settingsLabel");
    aboutLabel->setObjectName("aboutLabel");
    
    toolBar->addWidget(settingsLabel);
    toolBar->addWidget(aboutLabel);
    
    // 添加弹性空间，让菜单项靠左显示
    QWidget* spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    toolBar->addWidget(spacer);
    
    // 设置工具栏样式
    toolBar->setStyleSheet(
        "QToolBar { "
        "  background-color: #f8f9fa; "
        "  border-bottom: 2px solid #dee2e6; "
        "  padding: 0px; "                        // 移除内边距让标签自己控制位置
        "}"
        "QToolBar QLabel { "                      // 直接控制工具栏内标签的位置
        "  margin-top: 0px; "                     // 顶部边距为0
        "  margin-bottom: 0px; "                  // 底部边距为0
        "}"
    );
    
    qDebug() << "Using QToolBar with QLabel text for Linux - increased size";
#else
    // Windows下正常使用QMenuBar
    menuBar = new QMenuBar(this);
    menuBar->setFixedHeight(40);
    
    settingsAction = new QAction("设置", this);
    settingsAction->setStatusTip("配置工具路径");
    connect(settingsAction, &QAction::triggered, this, &Widget::showSettings);
    
    aboutAction = new QAction("关于", this);
    aboutAction->setStatusTip("查看软件信息");
    connect(aboutAction, &QAction::triggered, this, &Widget::showAbout);
    
    menuBar->addAction(settingsAction);
    menuBar->addAction(aboutAction);
    
    menuBar->setStyleSheet(
        "QMenuBar { "
        "  background-color: #f8f9fa; "
        "  border-bottom: 1px solid #dee2e6; "
        "  padding: 6px; "
        "  font-size: 14px; "
        "}"
        "QMenuBar::item { "
        "  padding: 6px 12px; "
        "  border-radius: 3px; "
        "  margin: 1px; "
        "}"
        "QMenu { "
        "  background-color: white; "
        "  border: 1px solid #bdc3c7; "
        "}"
        "QMenu::item { "
        "  padding: 8px 16px; "
        "}"
        "QMenu::item:selected { "
        "  background-color: #3498db; "
        "  color: white; "
        "}"
    );
#endif
}

QString Widget::autoDetectWinDeployQt()
{
    // 方法1: 通过qmake --version获取Qt安装路径
    QProcess qmakeProcess;
    qmakeProcess.start("qmake", QStringList() << "--version");
    
    if (qmakeProcess.waitForFinished(5000)) {
        QString output = qmakeProcess.readAllStandardOutput();
        
        // 解析输出，查找Qt库路径
        // 输出格式类似: "Using Qt version 6.9.0 in D:/Qt/6.9.0/msvc2022_64/lib"
        QRegularExpression regex(R"(Using Qt version .+ in (.+)/lib)");
        QRegularExpressionMatch match = regex.match(output);
        
        if (match.hasMatch()) {
            QString qtBinPath = match.captured(1) + "/bin";
            QString windeployqtPath = QDir(qtBinPath).filePath("windeployqt.exe");
            
            // 验证文件是否存在并可执行
            QFileInfo fileInfo(windeployqtPath);
            if (fileInfo.exists() && fileInfo.isFile() && fileInfo.isExecutable()) {
                // 进一步验证该windeployqt.exe是否能正常工作
                QProcess testProcess;
                testProcess.start(windeployqtPath, QStringList() << "--version");
                if (testProcess.waitForFinished(3000)) {
                    return QDir::toNativeSeparators(windeployqtPath);
                }
            }
        }
    }
    
    // 方法2: 如果qmake方法失败，尝试常见路径
    QStringList possiblePaths = {
        "C:/Qt/6.9.0/msvc2022_64/bin/windeployqt.exe",
        "C:/Qt/6.8.0/msvc2022_64/bin/windeployqt.exe",
        "C:/Qt/6.7.0/msvc2022_64/bin/windeployqt.exe",
        "C:/Qt/6.6.0/msvc2022_64/bin/windeployqt.exe",
        "C:/Qt/6.5.0/msvc2022_64/bin/windeployqt.exe",
        "C:/Qt/6.9.0/mingw_64/bin/windeployqt.exe",
        "C:/Qt/6.8.0/mingw_64/bin/windeployqt.exe",
        "C:/Qt/6.7.0/mingw_64/bin/windeployqt.exe",
        "C:/Qt/5.15.0/msvc2019_64/bin/windeployqt.exe",
        "C:/Qt/5.14.0/msvc2017_64/bin/windeployqt.exe",
        "D:/Qt/6.9.0/msvc2022_64/bin/windeployqt.exe",
        "D:/Qt/6.8.0/msvc2022_64/bin/windeployqt.exe",
        "D:/Qt/6.7.0/msvc2022_64/bin/windeployqt.exe"
    };
    
    // 方法3: 从环境变量QTDIR获取
    QString qtDir = QDir::fromNativeSeparators(qgetenv("QTDIR"));
    if (!qtDir.isEmpty()) {
        possiblePaths.prepend(qtDir + "/bin/windeployqt.exe");
    }
    
    // 方法4: 从PATH环境变量中查找
    QString pathEnv = qgetenv("PATH");
    QStringList paths = pathEnv.split(QDir::listSeparator(), Qt::SkipEmptyParts);
    for (const QString &path : paths) {
        QString candidate = QDir(path).filePath("windeployqt.exe");
        possiblePaths.append(candidate);
    }
    
    // 检查每个可能的路径
    for (const QString &path : possiblePaths) {
        QFileInfo fileInfo(path);
        if (fileInfo.exists() && fileInfo.isFile() && fileInfo.isExecutable()) {
            // 验证该文件是否可以正常执行
            QProcess testProcess;
            testProcess.start(path, QStringList() << "--version");
            if (testProcess.waitForFinished(3000)) {
                return QDir::toNativeSeparators(path);
            }
        }
    }
    
    return QString(); // 未找到
}

QString Widget::autoDetectInnoSetup()
{
    // 方法1: 检查系统PATH中的ISCC命令
    QProcess isccProcess;
    isccProcess.start("ISCC", QStringList() << "/?");
    
    if (isccProcess.waitForFinished(3000)) {
        QString output = isccProcess.readAllStandardOutput();
        QString error = isccProcess.readAllStandardError();
        
        // 如果输出包含Inno Setup相关信息，说明命令可用
        if (output.contains("Inno Setup", Qt::CaseInsensitive) || 
            error.contains("Inno Setup", Qt::CaseInsensitive)) {
            return "ISCC"; // 返回命令名，表示在PATH中可用
        }
    }
    
    // 方法2: 检查常见安装路径
    QStringList possiblePaths = {
        "C:/Program Files (x86)/Inno Setup 6/ISCC.exe",
        "C:/Program Files/Inno Setup 6/ISCC.exe",
        "C:/Program Files (x86)/Inno Setup 5/ISCC.exe", 
        "C:/Program Files/Inno Setup 5/ISCC.exe",
        "D:/Program Files (x86)/Inno Setup 6/ISCC.exe",
        "D:/Program Files/Inno Setup 6/ISCC.exe"
    };
    
    for (const QString &path : possiblePaths) {
        QFileInfo fileInfo(path);
        if (fileInfo.exists() && fileInfo.isFile() && fileInfo.isExecutable()) {
            // 验证该文件是否可以正常执行
            QProcess testProcess;
            testProcess.start(path, QStringList() << "/?");
            if (testProcess.waitForFinished(3000)) {
                QString output = testProcess.readAllStandardOutput();
                if (output.contains("Inno Setup", Qt::CaseInsensitive)) {
                    return QDir::toNativeSeparators(path);
                }
            }
        }
    }
    
    return QString(); // 未找到
}

bool Widget::isQtApplication(const QString &exePath)
{
    QFileInfo fileInfo(exePath);
    if (!fileInfo.exists() || !fileInfo.isFile()) {
        return false;
    }

#ifdef Q_OS_WIN
    // Windows下使用dumpbin检查依赖
    QProcess process;
    process.start("dumpbin", QStringList() << "/DEPENDENTS" << exePath);
    
    if (process.waitForFinished(5000)) {
        QString output = process.readAllStandardOutput();
        // 检查是否有Qt相关的DLL依赖
        if (output.contains("Qt6Core", Qt::CaseInsensitive) || 
            output.contains("Qt5Core", Qt::CaseInsensitive) ||
            output.contains("Qt6Gui", Qt::CaseInsensitive) ||
            output.contains("Qt5Gui", Qt::CaseInsensitive) ||
            output.contains("Qt6Widgets", Qt::CaseInsensitive) ||
            output.contains("Qt5Widgets", Qt::CaseInsensitive)) {
            return true;
        }
    }
    
    // 如果dumpbin不可用，检查同目录下是否有Qt DLL文件
    QDir exeDir = fileInfo.absoluteDir();
    QStringList qtDlls = {
        "Qt6Core.dll", "Qt5Core.dll",
        "Qt6Gui.dll", "Qt5Gui.dll", 
        "Qt6Widgets.dll", "Qt5Widgets.dll",
        "Qt6Network.dll", "Qt5Network.dll"
    };
    
    for (const QString &qtDll : qtDlls) {
        if (exeDir.exists(qtDll)) {
            return true;
        }
    }
#else
    // Linux下使用ldd检查动态链接依赖
    QProcess process;
    process.start("ldd", QStringList() << exePath);
    
    if (process.waitForFinished(5000)) {
        QString output = process.readAllStandardOutput();
        // 检查是否有Qt相关的共享库依赖
        if (output.contains("libQt6Core", Qt::CaseInsensitive) || 
            output.contains("libQt5Core", Qt::CaseInsensitive) ||
            output.contains("libQt6Gui", Qt::CaseInsensitive) ||
            output.contains("libQt5Gui", Qt::CaseInsensitive) ||
            output.contains("libQt6Widgets", Qt::CaseInsensitive) ||
            output.contains("libQt5Widgets", Qt::CaseInsensitive)) {
            return true;
        }
    }
    
    // 如果ldd不可用或者没有找到Qt依赖，检查同目录下是否有Qt共享库文件
    QDir exeDir = fileInfo.absoluteDir();
    QStringList qtLibs = {
        "libQt6Core.so", "libQt5Core.so",
        "libQt6Gui.so", "libQt5Gui.so", 
        "libQt6Widgets.so", "libQt5Widgets.so",
        "libQt6Network.so", "libQt5Network.so"
    };
    
    for (const QString &qtLib : qtLibs) {
        if (exeDir.exists(qtLib)) {
            return true;
        }
    }
#endif
    
    // 方法3: 尝试运行windeployqt来检测（如果配置了的话）
    QString windeployqtPath = settings->value("WinDeployQtPath").toString();
    if (!windeployqtPath.isEmpty() && isWinDeployQtExist(windeployqtPath)) {
        QProcess testProcess;
        testProcess.start(windeployqtPath, QStringList() << "--dry-run" << exePath);
        if (testProcess.waitForFinished(3000)) {
            // 如果windeployqt能成功处理，说明是Qt程序
            return testProcess.exitCode() == 0;
        }
    }
    
    return false; // 默认认为不是Qt程序
}

void Widget::runInnoSetupCompiler(const QString &issPath)
{
    // 首先尝试使用系统PATH中的ISCC命令
    QString isccCommand = "ISCC";
    
    // 测试ISCC是否在PATH中可用
    QProcess testProcess;
    testProcess.start(isccCommand, QStringList() << "-v");
    
    bool isccAvailable = false;
    if (testProcess.waitForFinished(3000)) {
        QString output = testProcess.readAllStandardOutput();
        if (output.contains("Inno Setup", Qt::CaseInsensitive)) {
            isccAvailable = true;
        }
    }
    
    // 如果PATH中没有ISCC，尝试查找安装路径
    if (!isccAvailable) {
        QStringList possiblePaths = {
            "C:/Program Files (x86)/Inno Setup 6/ISCC.exe",
            "C:/Program Files/Inno Setup 6/ISCC.exe",
            "C:/Program Files (x86)/Inno Setup 5/ISCC.exe", 
            "C:/Program Files/Inno Setup 5/ISCC.exe"
        };
        
        for (const QString &path : possiblePaths) {
            if (QFileInfo(path).exists()) {
                isccCommand = path;
                isccAvailable = true;
                break;
            }
        }
    }
    
    if (!isccAvailable) {
        QMessageBox::information(this, "提示", 
            "未找到Inno Setup编译器(ISCC.exe)。\n\n"
            "请确保：\n"
            "1. 已安装Inno Setup\n"
            "2. ISCC命令在系统PATH中可用\n"
            "3. 或者将ISCC.exe添加到系统PATH\n\n"
            "脚本已生成，位置：\n" + issPath + "\n\n"
            "您可以手动用Inno Setup打开此脚本进行编译。");
        
        // 尝试打开脚本文件
        openIssFile(issPath);
        return;
    }
    
    // 运行编译器
    QProcess *compileProcess = new QProcess(this);
    
    // 连接信号以处理编译结果
    connect(compileProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [this, issPath, compileProcess](int exitCode, QProcess::ExitStatus exitStatus) {
                compileProcess->deleteLater();
                
                if (exitCode == 0 && exitStatus == QProcess::NormalExit) {
                    // 编译成功
                    QString outputDir = QFileInfo(issPath).absolutePath();
                    QString exeName = QFileInfo(issPath).baseName();
                    
                    QMessageBox::StandardButton reply = QMessageBox::question(this, 
                        "编译成功", 
                        QString("安装包编译完成！\n\n输出目录：%1\n\n是否打开输出目录？").arg(outputDir),
                        QMessageBox::Yes | QMessageBox::No);
                        
                    if (reply == QMessageBox::Yes) {
                        QDesktopServices::openUrl(QUrl::fromLocalFile(outputDir));
                    }
                } else {
                    // 编译失败
                    QString error = compileProcess->readAllStandardError();
                    QString output = compileProcess->readAllStandardOutput();
                    QMessageBox::critical(this, "编译失败", 
                        QString("安装包编译失败！\n\n错误信息：\n%1\n\n输出信息：\n%2").arg(error, output));
                }
            });
    
    // 显示编译进度对话框
    QMessageBox *progressBox = new QMessageBox(this);
    progressBox->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    progressBox->setIcon(QMessageBox::Information);
    progressBox->setWindowTitle("正在编译");
    progressBox->setText("正在编译安装包，请稍候...");
    progressBox->setStandardButtons(QMessageBox::NoButton);
    progressBox->show();
    
    // 编译完成后关闭进度对话框
    connect(compileProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            progressBox, &QMessageBox::close);
    
    // 启动编译过程
    compileProcess->start(isccCommand, QStringList() << issPath);
}

void Widget::createStyledDialog(QDialog *dialog, const QString &title)
{
    dialog->setWindowTitle(title);
    dialog->setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
    dialog->setAttribute(Qt::WA_DeleteOnClose, false);
    
    // 设置对话框样式
    dialog->setStyleSheet(
        "QDialog {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "              stop:0 #ffffff, stop:1 #f0f5ff);"
        "    border-radius: 12px;"
        "    border: 1px solid #d0e0ff;"
        "}"
        "QLabel {"
        "    color: #2c3e50;"
        "    font-family: 'Microsoft YaHei';"
        "}"
        "QLineEdit {"
        "    border: 1px solid #bdc3c7;"
        "    border-radius: 6px;"
        "    padding: 8px;"
        "    background-color: white;"
        "    font-size: 13px;"
        "}"
        "QLineEdit:focus {"
        "    border: 2px solid #3498db;"
        "}"
        "QPushButton {"
        "    background-color: #3498db;"
        "    color: white;"
        "    border: none;"
        "    padding: 8px 16px;"
        "    border-radius: 6px;"
        "    font-weight: bold;"
        "    font-size: 13px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #2980b9;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #1d6fa5;"
        "}"
        "QTextEdit {"
        "    border: 1px solid #bdc3c7;"
        "    border-radius: 6px;"
        "    background-color: white;"
        "    font-family: 'Microsoft YaHei';"
        "    font-size: 12px;"
        "    line-height: 1.5;"
        "}"
    );
}

void Widget::showSettings()
{
    QDialog *settingsDialog = new QDialog(this);
    createStyledDialog(settingsDialog, "设置");
    settingsDialog->resize(600, 400);
    
    QVBoxLayout *layout = new QVBoxLayout(settingsDialog);
    layout->setSpacing(15);
    layout->setContentsMargins(20, 20, 20, 20);
    
    // 标题
    QLabel *titleLabel = new QLabel("软件路径设置", settingsDialog);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(14);
    titleFont.setBold(false);
    titleLabel->setFont(titleFont);
    titleLabel->setAlignment(Qt::AlignCenter);
    
#ifdef Q_OS_WIN
    // Windows版本的设置
    // WinDeployQt路径设置
    QLabel *winDeployLabel = new QLabel("WinDeployQt 路径:", settingsDialog);
    QLineEdit *winDeployPathEdit = new QLineEdit(settingsDialog);
    winDeployPathEdit->setText(settings->value("WinDeployQtPath").toString());
    winDeployPathEdit->setReadOnly(true);
    winDeployPathEdit->setStyleSheet(LINE_EDIT_STYLE);  // 设置正常黑色文字
    
    QPushButton *winDeployBrowseButton = new QPushButton("浏览", settingsDialog);
    
    QHBoxLayout *winDeployLayout = new QHBoxLayout();
    winDeployLayout->addWidget(winDeployPathEdit);
    winDeployLayout->addWidget(winDeployBrowseButton);
    
    // Inno Setup编译器路径设置
    QLabel *innoSetupLabel = new QLabel("Inno Setup 编译器路径:", settingsDialog);
    QLineEdit *innoSetupPathEdit = new QLineEdit(settingsDialog);
    innoSetupPathEdit->setText(settings->value("InnoSetupPath").toString());
    innoSetupPathEdit->setReadOnly(true);
    innoSetupPathEdit->setStyleSheet(LINE_EDIT_STYLE);  // 设置正常黑色文字
    
    QPushButton *innoSetupBrowseButton = new QPushButton("浏览", settingsDialog);
    
    QHBoxLayout *innoSetupLayout = new QHBoxLayout();
    innoSetupLayout->addWidget(innoSetupPathEdit);
    innoSetupLayout->addWidget(innoSetupBrowseButton);
    
#elif defined(Q_OS_LINUX)
    // Linux版本的设置
    // LinuxDeployQt路径设置
    QLabel *linuxDeployLabel = new QLabel("LinuxDeployQt 路径:", settingsDialog);
    QLineEdit *linuxDeployPathEdit = new QLineEdit(settingsDialog);
    linuxDeployPathEdit->setText(settings->value("LinuxDeployQtPath").toString());
    linuxDeployPathEdit->setReadOnly(true);
    linuxDeployPathEdit->setStyleSheet(LINE_EDIT_STYLE);  // 设置正常黑色文字
    
    QPushButton *linuxDeployBrowseButton = new QPushButton("浏览", settingsDialog);
    
    QHBoxLayout *linuxDeployLayout = new QHBoxLayout();
    linuxDeployLayout->addWidget(linuxDeployPathEdit);
    linuxDeployLayout->addWidget(linuxDeployBrowseButton);
    
    // AppImageTool路径设置
    QLabel *appImageLabel = new QLabel("AppImageTool 路径:", settingsDialog);
    QLineEdit *appImagePathEdit = new QLineEdit(settingsDialog);
    appImagePathEdit->setText(settings->value("AppImageToolPath").toString());
    appImagePathEdit->setReadOnly(true);
    appImagePathEdit->setStyleSheet(LINE_EDIT_STYLE);  // 设置正常黑色文字
    
    QPushButton *appImageBrowseButton = new QPushButton("浏览", settingsDialog);
    
    QHBoxLayout *appImageLayout = new QHBoxLayout();
    appImageLayout->addWidget(appImagePathEdit);
    appImageLayout->addWidget(appImageBrowseButton);
#endif
    
    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *autoDetectButton = new QPushButton("自动检测全部", settingsDialog);
    QPushButton *okButton = new QPushButton("确定", settingsDialog);
    QPushButton *cancelButton = new QPushButton("取消", settingsDialog);
    
    buttonLayout->addWidget(autoDetectButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);
    
    // 添加到主布局
    layout->addWidget(titleLabel);
    layout->addSpacing(10);
    
#ifdef Q_OS_WIN
    layout->addWidget(winDeployLabel);
    layout->addLayout(winDeployLayout);
    layout->addSpacing(10);
    layout->addWidget(innoSetupLabel);
    layout->addLayout(innoSetupLayout);
#elif defined(Q_OS_LINUX)
    layout->addWidget(linuxDeployLabel);
    layout->addLayout(linuxDeployLayout);
    layout->addSpacing(10);
    layout->addWidget(appImageLabel);
    layout->addLayout(appImageLayout);
#endif
    
    layout->addSpacing(20);
    layout->addLayout(buttonLayout);
    
    // 连接信号
#ifdef Q_OS_WIN
    connect(winDeployBrowseButton, &QPushButton::clicked, [=]() {
        QString newPath = getValidWindeployqtPath(settingsDialog);
        if (!newPath.isEmpty()) {
            winDeployPathEdit->setText(newPath);
        }
    });
    
    connect(innoSetupBrowseButton, &QPushButton::clicked, [=]() {
        QString selectedPath = QFileDialog::getOpenFileName(
            settingsDialog,
            "选择 Inno Setup 编译器",
            QCoreApplication::applicationDirPath(),
            "ISCC (ISCC.exe);;所有文件 (*.*)"
        );

        if (!selectedPath.isEmpty()) {
            QFileInfo fileInfo(selectedPath);
            if (fileInfo.fileName().compare("ISCC.exe", Qt::CaseInsensitive) != 0) {
                QMessageBox::warning(settingsDialog, "无效文件", "必须选择 ISCC.exe 文件！");
                return;
            }

            // 验证文件是否可执行
            QProcess testProcess;
            testProcess.start(selectedPath, QStringList() << "/?");
            if (!testProcess.waitForFinished(3000)) {
                QMessageBox::warning(settingsDialog, "无效文件", "文件无法执行，请选择有效的 ISCC.exe！");
                return;
            }

            QString output = testProcess.readAllStandardOutput();
            if (!output.contains("Inno Setup", Qt::CaseInsensitive)) {
                QMessageBox::warning(settingsDialog, "无效文件", "这不是有效的 Inno Setup 编译器！");
                return;
            }

            innoSetupPathEdit->setText(QDir::toNativeSeparators(selectedPath));
        }
    });
    
#elif defined(Q_OS_LINUX)
    connect(linuxDeployBrowseButton, &QPushButton::clicked, [=]() {
        QString selectedPath = QFileDialog::getOpenFileName(
            settingsDialog,
            "选择 LinuxDeployQt",
            QCoreApplication::applicationDirPath(),
            "LinuxDeployQt (linuxdeployqt);;所有文件 (*.*)"
        );

        if (!selectedPath.isEmpty()) {
            // 验证文件是否可执行
            QProcess testProcess;
            testProcess.start(selectedPath, QStringList() << "--version");
            if (!testProcess.waitForFinished(3000)) {
                QMessageBox::warning(settingsDialog, "无效文件", "文件无法执行，请选择有效的 linuxdeployqt！");
                return;
            }

            QString output = testProcess.readAllStandardOutput();
            QString error = testProcess.readAllStandardError();
            if (!output.contains("linuxdeployqt", Qt::CaseInsensitive) && 
                !error.contains("linuxdeployqt", Qt::CaseInsensitive)) {
                QMessageBox::warning(settingsDialog, "无效文件", "这不是有效的 LinuxDeployQt！");
                return;
            }

            linuxDeployPathEdit->setText(QDir::toNativeSeparators(selectedPath));
        }
    });
    
    connect(appImageBrowseButton, &QPushButton::clicked, [=]() {
        QString selectedPath = QFileDialog::getOpenFileName(
            settingsDialog,
            "选择 AppImageTool",
            QCoreApplication::applicationDirPath(),
            "AppImageTool (appimagetool);;所有文件 (*.*)"
        );

        if (!selectedPath.isEmpty()) {
            // 验证文件是否可执行
            QProcess testProcess;
            testProcess.start(selectedPath, QStringList() << "--version");
            if (!testProcess.waitForFinished(3000)) {
                QMessageBox::warning(settingsDialog, "无效文件", "文件无法执行，请选择有效的 appimagetool！");
                return;
            }

            QString output = testProcess.readAllStandardOutput();
            QString error = testProcess.readAllStandardError();
            if (!output.contains("appimagetool", Qt::CaseInsensitive) && 
                !error.contains("appimagetool", Qt::CaseInsensitive)) {
                QMessageBox::warning(settingsDialog, "无效文件", "这不是有效的 AppImageTool！");
                return;
            }

            appImagePathEdit->setText(QDir::toNativeSeparators(selectedPath));
        }
    });
#endif
    
    connect(autoDetectButton, &QPushButton::clicked, [=]() {
        QString message = "自动检测结果：\n\n";
#ifdef Q_OS_WIN
        // 检测WinDeployQt
        QString winDeployPath = autoDetectWinDeployQt();
        if (!winDeployPath.isEmpty()) {
            winDeployPathEdit->setText(winDeployPath);
            settings->setValue("WinDeployQtPath", winDeployPath);
        }
        
        // 检测Inno Setup
        QString innoSetupPath = autoDetectInnoSetup();
        if (!innoSetupPath.isEmpty()) {
            innoSetupPathEdit->setText(innoSetupPath);
            settings->setValue("InnoSetupPath", innoSetupPath);
        }
        
        message += QString("WinDeployQt: %1\n").arg(winDeployPath.isEmpty() ? "未找到" : "已找到");
        message += QString("Inno Setup: %1").arg(innoSetupPath.isEmpty() ? "未找到" : "已找到");
#elif defined(Q_OS_LINUX)
        // 检测LinuxDeployQt
        QString linuxDeployPath = getValidLinuxdeployqtPath();
        if (!linuxDeployPath.isEmpty()) {
            linuxDeployPathEdit->setText(linuxDeployPath);
            settings->setValue("LinuxDeployQtPath", linuxDeployPath);
        }
        
        // 检测AppImageTool
        QString appImagePath = getValidAppimagetoolPath();
        if (!appImagePath.isEmpty()) {
            appImagePathEdit->setText(appImagePath);
            settings->setValue("AppImageToolPath", appImagePath);
        }
        
        message += QString("LinuxDeployQt: %1\n").arg(linuxDeployPath.isEmpty() ? "未找到" : "已找到");
        message += QString("AppImageTool: %1").arg(appImagePath.isEmpty() ? "未找到" : "已找到");
#endif
        
        QMessageBox::information(settingsDialog, "自动检测完成", message);
    });
    
    connect(okButton, &QPushButton::clicked, [=]() {
#ifdef Q_OS_WIN
        settings->setValue("WinDeployQtPath", winDeployPathEdit->text().trimmed());
        settings->setValue("InnoSetupPath", innoSetupPathEdit->text().trimmed());
#elif defined(Q_OS_LINUX)
        settings->setValue("LinuxDeployQtPath", linuxDeployPathEdit->text().trimmed());
        settings->setValue("AppImageToolPath", appImagePathEdit->text().trimmed());
#endif
        QMessageBox::information(settingsDialog, "设置成功", "软件路径设置已更新！");
        settingsDialog->accept();
    });
    
    connect(cancelButton, &QPushButton::clicked, settingsDialog, &QDialog::reject);
    
    settingsDialog->exec();
    delete settingsDialog;
}

void Widget::showAbout()
{
    QDialog *aboutDialog = new QDialog(this);
    createStyledDialog(aboutDialog, "关于 AutoPack");
    aboutDialog->resize(420, 400); // 减小高度
    
    QVBoxLayout *layout = new QVBoxLayout(aboutDialog);
    layout->setSpacing(15); // 减小间距
    layout->setContentsMargins(30, 25, 30, 25); // 减小边距
    
    // 居中的图标
    QLabel *iconLabel = new QLabel(aboutDialog);
    iconLabel->setAlignment(Qt::AlignCenter);
    QPixmap icon(":/icons/package.png");
    if (!icon.isNull()) {
        iconLabel->setPixmap(icon.scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation)); // 稍微小一点
    } else {
        // 如果没有图标，创建一个简单的占位图标
        QPixmap placeholder(64, 64);
        placeholder.fill(Qt::transparent);
        QPainter painter(&placeholder);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setBrush(QColor("#3498db"));
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(0, 0, 64, 64);
        painter.setPen(QPen(Qt::white, 3));
        painter.setFont(QFont("Arial", 20, QFont::Bold)); // 调整字体大小
        painter.drawText(placeholder.rect(), Qt::AlignCenter, "AP");
        iconLabel->setPixmap(placeholder);
    }
    
    // 软件名称
    QLabel *nameLabel = new QLabel("AutoPack", aboutDialog);
    nameLabel->setAlignment(Qt::AlignCenter);
    QFont nameFont = nameLabel->font();
    nameFont.setPointSize(20); // 稍微小一点
    nameFont.setBold(true);
    nameLabel->setFont(nameFont);
    nameLabel->setStyleSheet("color: #2c3e50; margin: 5px 0;"); // 减小边距
    
    // 版本信息
    QLabel *versionLabel = new QLabel("版本 1.0.0", aboutDialog);
    versionLabel->setAlignment(Qt::AlignCenter);
    versionLabel->setStyleSheet("color: #000000; font-size: 14px; font-weight: normal; margin-bottom: 5px;"); // 黑色正常字体
    
    // 分割线
    QFrame *line = new QFrame(aboutDialog);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    line->setStyleSheet("color: #ecf0f1;");
    
    // 功能介绍
    QLabel *descLabel = new QLabel("基于Qt的Windows应用程序一键打包工具", aboutDialog);
    descLabel->setAlignment(Qt::AlignCenter);
    descLabel->setStyleSheet("color: #000000; font-size: 13px; font-weight: normal; margin: 8px 0;"); // 黑色正常字体
    descLabel->setWordWrap(true);
    
    // 技术信息
    QLabel *techLabel = new QLabel(
        "开发框架: Qt 6.9.0 • C++17\n"
        "构建系统: CMake • 打包工具: Inno Setup", aboutDialog);
    techLabel->setAlignment(Qt::AlignCenter);
    techLabel->setStyleSheet("color: #000000; font-size: 11px; font-weight: normal; margin: 12px 0;"); // 黑色正常字体
    
    // 开发者信息
    QLabel *developerLabel = new QLabel("开发者: 工具组 - 张纪生", aboutDialog);
    developerLabel->setAlignment(Qt::AlignCenter);
    developerLabel->setStyleSheet("color: #2c3e50; font-size: 12px; font-weight: normal;");
    
    // 版权信息
    QLabel *copyrightLabel = new QLabel("© 2025 AutoPack. All rights reserved.", aboutDialog);
    copyrightLabel->setAlignment(Qt::AlignCenter);
    copyrightLabel->setStyleSheet("color: #95a5a6; font-size: 10px;");
    
    // 关闭按钮
    QPushButton *closeButton = new QPushButton("关闭", aboutDialog);
    closeButton->setMinimumSize(100, 35);
    closeButton->setStyleSheet(
        "QPushButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #3498db, stop:1 #2980b9);"
        "    color: white;"
        "    border: none;"
        "    border-radius: 6px;"
        "    font-weight: normal;"
        "    font-size: 13px;"
        "}"
        "QPushButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #5dade2, stop:1 #3498db);"
        "}"
        "QPushButton:pressed {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #2980b9, stop:1 #1f618d);"
        "}"
    );
    
    // 居中关闭按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(closeButton);
    buttonLayout->addStretch();
    
    // 添加所有组件到主布局
    layout->addWidget(iconLabel);
    layout->addSpacing(5); // 减小间距
    layout->addWidget(nameLabel);
    layout->addWidget(versionLabel);
    layout->addWidget(line);
    layout->addWidget(descLabel);
    layout->addWidget(techLabel);
    layout->addWidget(developerLabel);
    layout->addStretch();
    layout->addWidget(copyrightLabel);
    layout->addSpacing(10); // 减小间距
    layout->addLayout(buttonLayout);
    
    connect(closeButton, &QPushButton::clicked, aboutDialog, &QDialog::accept);
    
    aboutDialog->exec();
    delete aboutDialog;
}

#ifdef Q_OS_LINUX
QString Widget::getValidLinuxdeployqtPath() {
    // 首先检查设置中的路径
    QSettings settings;
    QString settingsPath = settings.value("LinuxDeployQtPath").toString();
    
    if (!settingsPath.isEmpty()) {
        QFileInfo fileInfo(settingsPath);
        if (fileInfo.exists() && fileInfo.isExecutable()) {
            // 验证文件是否真的是linuxdeployqt
            QProcess testProcess;
            testProcess.start(settingsPath, QStringList() << "--version");
            testProcess.waitForFinished(3000);
            QString output = testProcess.readAllStandardOutput();
            QString error = testProcess.readAllStandardError();
            if (output.contains("linuxdeployqt", Qt::CaseInsensitive) || 
                error.contains("linuxdeployqt", Qt::CaseInsensitive)) {
                return settingsPath;
            }
        }
    }
    
    // 在PATH中查找linuxdeployqt
    QStringList searchPaths = QString(qgetenv("PATH")).split(":");
    searchPaths << "/usr/local/bin" << "/usr/bin" << "/opt/linuxdeployqt";
    
    for (const QString &path : searchPaths) {
        QString linuxdeployqtPath = QDir(path).filePath("linuxdeployqt");
        QFileInfo fileInfo(linuxdeployqtPath);
        if (fileInfo.exists() && fileInfo.isExecutable()) {
            // 验证是否是真正的linuxdeployqt
            QProcess testProcess;
            testProcess.start(linuxdeployqtPath, QStringList() << "--version");
            testProcess.waitForFinished(3000);
            QString output = testProcess.readAllStandardOutput();
            QString error = testProcess.readAllStandardError();
            if (output.contains("linuxdeployqt", Qt::CaseInsensitive) || 
                error.contains("linuxdeployqt", Qt::CaseInsensitive)) {
                return linuxdeployqtPath;
            }
        }
    }
    
    return QString(); // 未找到
}

QString Widget::getValidAppimagetoolPath() {
    // 首先检查设置中的路径
    QSettings settings;
    QString settingsPath = settings.value("AppImageToolPath").toString();
    
    if (!settingsPath.isEmpty()) {
        QFileInfo fileInfo(settingsPath);
        if (fileInfo.exists() && fileInfo.isExecutable()) {
            // 验证文件是否真的是appimagetool
            QProcess testProcess;
            testProcess.start(settingsPath, QStringList() << "--version");
            testProcess.waitForFinished(3000);
            QString output = testProcess.readAllStandardOutput();
            QString error = testProcess.readAllStandardError();
            if (output.contains("appimagetool", Qt::CaseInsensitive) || 
                error.contains("appimagetool", Qt::CaseInsensitive)) {
                return settingsPath;
            }
        }
    }
    
    // 在PATH中查找appimagetool
    QStringList searchPaths = QString(qgetenv("PATH")).split(":");
    searchPaths << "/usr/local/bin" << "/usr/bin" << "/opt/appimage";
    
    for (const QString &path : searchPaths) {
        QString appimagetoolPath = QDir(path).filePath("appimagetool");
        QFileInfo fileInfo(appimagetoolPath);
        if (fileInfo.exists() && fileInfo.isExecutable()) {
            // 验证是否是真正的appimagetool
            QProcess testProcess;
            testProcess.start(appimagetoolPath, QStringList() << "--version");
            testProcess.waitForFinished(3000);
            QString output = testProcess.readAllStandardOutput();
            QString error = testProcess.readAllStandardError();
            if (output.contains("appimagetool", Qt::CaseInsensitive) || 
                error.contains("appimagetool", Qt::CaseInsensitive)) {
                return appimagetoolPath;
            }
        }
    }
    
    return QString(); // 未找到
}

bool Widget::isAppimagetoolInstalled() {
    // 检查appimagetool是否已安装
    QString appimagetoolPath = getValidAppimagetoolPath();
    return !appimagetoolPath.isEmpty();
}

void Widget::downloadAppimagetool() {
    // 显示下载提示
    QMessageBox::information(this, "自动下载", 
        "未检测到AppImageTool，将自动下载并安装。\n这可能需要几分钟时间，请稍候...");
    
    // 异步下载appimagetool
    QProcess *downloadProcess = new QProcess(this);
    
    // 设置下载完成后的处理
    connect(downloadProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, [this, downloadProcess](int exitCode, QProcess::ExitStatus exitStatus) {
        
        if (exitCode == 0 && exitStatus == QProcess::NormalExit) {
            qDebug() << "AppImageTool download completed successfully";
            
            // 设置可执行权限
            QProcess *chmodProcess = new QProcess(this);
            chmodProcess->start("chmod", QStringList() << "+x" << "/tmp/appimagetool-x86_64.AppImage");
            chmodProcess->waitForFinished(5000);
            
            // 移动到系统路径 - 尝试不同的方式
            QProcess *moveProcess = new QProcess(this);
            
            // 首先尝试移动到 /usr/local/bin
            QString moveCommand = QString("pkexec mv /tmp/appimagetool-x86_64.AppImage /usr/local/bin/appimagetool");
            moveProcess->start("sh", QStringList() << "-c" << moveCommand);
            moveProcess->waitForFinished(30000); // 等待用户输入密码
            
            if (moveProcess->exitCode() == 0) {
                qDebug() << "AppImageTool installed to /usr/local/bin/appimagetool";
                
                // 验证安装
                if (isAppimagetoolInstalled()) {
                    QMessageBox::information(this, "安装成功", 
                        "AppImageTool 已成功下载并安装！\n现在可以正常使用AppImage打包功能。");
                } else {
                    QMessageBox::warning(this, "安装验证失败", 
                        "AppImageTool 下载完成但验证失败，请手动检查安装。");
                }
            } else {
                // 如果移动到系统目录失败，尝试放到用户目录
                QString userBinDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.local/bin";
                QDir().mkpath(userBinDir);
                
                QString userMoveCommand = QString("mv /tmp/appimagetool-x86_64.AppImage %1/appimagetool").arg(userBinDir);
                QProcess *userMoveProcess = new QProcess(this);
                userMoveProcess->start("sh", QStringList() << "-c" << userMoveCommand);
                userMoveProcess->waitForFinished(5000);
                
                if (userMoveProcess->exitCode() == 0) {
                    qDebug() << "AppImageTool installed to user bin directory";
                    QMessageBox::information(this, "安装完成", 
                        QString("AppImageTool 已安装到用户目录：\n%1/appimagetool\n\n"
                                "请确保该目录在您的PATH环境变量中。").arg(userBinDir));
                } else {
                    QMessageBox::warning(this, "安装失败", 
                        "AppImageTool 下载成功但安装失败。\n请手动安装或检查权限设置。");
                }
                
                userMoveProcess->deleteLater();
            }
            
            chmodProcess->deleteLater();
            moveProcess->deleteLater();
        } else {
            qDebug() << "AppImageTool download failed:" << downloadProcess->readAllStandardError();
            QMessageBox::warning(this, "下载失败", 
                "AppImageTool 下载失败。\n请检查网络连接或手动安装：\n"
                "wget https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage");
        }
        
        downloadProcess->deleteLater();
    });
    
    // 开始下载
    qDebug() << "Starting AppImageTool download...";
    downloadProcess->start("wget", QStringList() 
        << "-O" << "/tmp/appimagetool-x86_64.AppImage"
        << "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage");
}

void Widget::onAppImagePackagingFinished(bool success, const QString& outputPath, const QString& errorMsg) {
    if (success) {
        // 打包成功
        progressBar->setValue(100);
        statusLabel->setText("✅ AppImage 打包完成！");
        updatePackageButtonState("打包完成！", false);
        
        // 2秒后重置按钮状态并询问是否打开目录
        QTimer::singleShot(2000, this, [this, outputPath]() {
            resetPackageButtonState();
            
            // 询问是否打开输出目录
            QMessageBox::StandardButton reply = QMessageBox::question(this, 
                "打包完成", 
                QString("AppImage 打包完成！\n\n输出目录：%1\n\n是否打开输出目录？").arg(outputPath),
                QMessageBox::Yes | QMessageBox::No);
                
            if (reply == QMessageBox::Yes) {
                QDesktopServices::openUrl(QUrl::fromLocalFile(outputPath));
            }
        });
    } else {
        // 打包失败
        progressBar->setValue(0);
        statusLabel->setText("❌ AppImage 打包失败");
        updatePackageButtonState("打包失败", false);
        
        // 显示错误信息
        showError(errorMsg);
        
        // 2秒后重置按钮状态
        QTimer::singleShot(2000, this, [this]() {
            resetPackageButtonState();
        });
    }
}

#endif
